package main

import (
	"fmt"
	"sync"
)

var total int = 10
var wg sync.WaitGroup
var rwLock sync.RWMutex

/** 读写锁: 对于大多数web系统来说都是读多写少 */

func read() {
	defer wg.Done()
	rwLock.RLock()

	fmt.Println("开始读取数据:", total)
	fmt.Println("读取成功")

	rwLock.RUnlock()
}

func write() {
	defer wg.Done()
	rwLock.Lock()

	fmt.Println("开始修改数据, 原total值:", total)
	total += 1
	fmt.Println("修改成功")

	rwLock.Unlock()
}

func main() {
	wg.Add(120)
	for i := 0; i < 100; i++ {
		go read()
	}
	for i := 0; i < 20; i++ {
		go write()
	}
	wg.Wait()
	fmt.Println("end:", total) // end: 30
}
